package com.cookie.springcloud.controller;

import com.cookie.springcloud.service.PaymentHystrixService;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;


@RestController
@Slf4j
@DefaultProperties(defaultFallback = "payment_Global_fallbackMethod")
public class OrderHystirxController
{
    @Resource
    private PaymentHystrixService paymentHystrixService;

    @GetMapping("/consumer/payment/hystrix/ok/{id}")
    public String paymentInfo_OK(@PathVariable("id") Integer id)
    {
        String result = paymentHystrixService.paymentInfo_OK(id);
        return result;
    }

    //controller配置的timeoutInMilliseconds不生效是因为，paymentHystrixService被注解
    //@FeignClient标注了，

    /**
     * 官网解释“Feign将使用断路器包装所有方法”，也就是将@FeignClient标记的那个service接口
     * 下所有的方法进行了hystrix包装（类似于在这些方法上加了一个@HystrixCommand），这些方
     * 法会应用一个默认的超时时间为1s，所以你的service方法也有一个1s的超时时间，service执行超过1秒
     * 就会报异常，controller立马进入备用方法，controller上那个3秒那超时时间就没有效果了
     * @param id
     * @return
     */
    @GetMapping("/consumer/payment/hystrix/timeout/{id}")
    @HystrixCommand(fallbackMethod = "paymentTimeOutFallbackMethod",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000")
    })
    public String paymentInfo_TimeOut(@PathVariable("id") Integer id)
    {
//        try {
////            TimeUnit.SECONDS.sleep(4);
////        } catch (InterruptedException e) {
////            e.printStackTrace();
////        }
        String result = paymentHystrixService.paymentInfo_TimeOut(id);
        System.out.println(result);
        return result;
    }

    public String paymentTimeOutFallbackMethod(@PathVariable("id") Integer id)
    {
        return "我是消费者80,对方支付系统繁忙请10秒钟后再试或者自己运行出错请检查自己,o(╥﹏╥)o";
    }

    public String payment_Global_fallbackMethod()
    {
        return "Global异常处理信息，请稍后再试，/(ㄒoㄒ)/~~";
    }
}